package ping.pay.me.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import org.json.JSONException;
import ping.pay.me.R;
import ping.pay.me.common.Goods;

import java.util.ArrayList;
import java.util.HashMap;

import com.ryantang.pulllistview.RTPullListView;
import com.ryantang.pulllistview.RTPullListView.OnRefreshListener;
import ping.pay.me.web.HttpConnectionManager;

/**
 * Created by install on 14/12/14.
 */
public class GoodsListActivity extends Activity {
    private static final int INTERNET_FAILURE = -1;
    private static final int LOAD_SUCCESS = 1;
    private static final int LOAD_MORE_SUCCESS = 3;
    private static final int NO_MORE_INFO = 4;
    private static final int LOAD_NEW_INFO = 5;

    private RTPullListView mGoodsList;
    private ProgressBar moreProgressBar;
    ImageView imageView;

    private ArrayList<HashMap<String, Object>> items;
    private SimpleAdapter adapter;
    private HashMap<String, Object> map;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_list_activity);

        mGoodsList = (RTPullListView) findViewById(R.id.goods_list_lv);

        Goods goods = new Goods("萌妹子头像", R.drawable.icon);

        map = new HashMap<String, Object>();
        map.put("img", goods.getPicId());
        map.put("title", goods.getGoodsName());
        items = new ArrayList<HashMap<String, Object>>();
        items.add(map);
        items.add(map);
        items.add(map);
        items.add(map);
        items.add(map);

        adapter = new SimpleAdapter(this, items, R.layout.goods_item,
                new String[] { "img", "title" }, new int[] { R.id.img,
                R.id.title });
        mGoodsList.setAdapter(adapter);

        // 添加listview底部获取更多按钮（可自定义）
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.list_footview, null);
        RelativeLayout footerView = (RelativeLayout) view
                .findViewById(R.id.list_footview);
        moreProgressBar = (ProgressBar) view.findViewById(R.id.footer_progress);

        Log.d("003", mGoodsList + "=====" + footerView + "");
        mGoodsList.addFooterView(footerView);

        // 下拉刷新监听器
        mGoodsList.setonRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                            items.clear();
                            for (int i = 0; i < 5; i++) {
                                items.add(map);
                            }
                            myHandler.sendEmptyMessage(LOAD_NEW_INFO);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        // 获取跟多监听器
        footerView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                moreProgressBar.setVisibility(View.VISIBLE);

                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                            for (int i = 0; i < 1; i++) {
                                items.add(map);
                            }
                            myHandler.sendEmptyMessage(LOAD_MORE_SUCCESS);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        mGoodsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,
                                    int i, long l) {
                startActivity(new Intent(GoodsListActivity.this,
                        GoodsInfoActivity.class));
            }
        });

        imageView = (ImageView)findViewById(R.id.http_img);

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Log.d("tag","loading...");
                    Message msg = new Message();
                    msg.obj = loadImg("http://pingplus.sinaapp.com/api/?category=img&id=1&from=androidqq");
                    Log.d("tag","finish");
                    msg.what = 888;
                    myHandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    // 结果处理
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOAD_MORE_SUCCESS:
                    moreProgressBar.setVisibility(View.GONE);
                    adapter.notifyDataSetChanged();
                    mGoodsList.setSelectionfoot();
                    break;

                case LOAD_NEW_INFO:
                    adapter.notifyDataSetChanged();
                    mGoodsList.onRefreshComplete();
                    break;
                case 888:
                    imageView.setImageBitmap((Bitmap)msg.obj);
                default:
                    break;
            }
        }

    };

    private Bitmap loadImg(String urlPath){
        try {
            Log.d("tag","connect");
            String jsonStr = HttpConnectionManager.readParse(this,urlPath);
            Log.d("tag","startAnalysis");

            HashMap<String,Object> map = HttpConnectionManager.analysis(jsonStr);
            Log.d("tag","finishAnalysis");
            String imgUrl = (String)map.get("img");
            Bitmap bitmap = HttpConnectionManager.getImage(imgUrl);
            Log.d("tag","getImg");
            return bitmap;
        }catch (JSONException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}